package com.ws.mbp.springsecuritydemo.controller;

import com.ws.mbp.springsecuritydemo.bean.Users;
import com.ws.mbp.springsecuritydemo.service.UsersService;
import com.ws.mbp.springsecuritydemo.utils.JwtUtils;
import com.ws.mbp.springsecuritydemo.utils.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 *     Spring Security 的认证流程大致如下：
 *
 */
@RestController
@RequestMapping("/api/auth")
@Tag(name = "用户认证", description = "用户认证接口")   //---@Api  ===@Tag
public class LoginAction {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    UsersService usersService;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册接口")   //@ApiOperation ---@Operation
    public ResponseEntity<Map<String, String>> register(@RequestBody Users user) {

        user.setUserPass(passwordEncoder.encode(user.getUserPass()));
        usersService.add(user);
        System.out.println("角色先不处理了");
        Map<String, String> response = new HashMap<>();
        response.put("message", "User registered successfully");
        return ResponseEntity.ok(response);
    }
    @PostMapping("/login")
    @Operation(summary = "用户登录" ,  description = "用户登录接口")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "401", description = "token异常"),
            @ApiResponse(responseCode = "403", description = "鉴权失败 没有权限")
    })
    public R authenticate(@RequestBody Users user) {
        System.out.println(user+"进入了登录控制器。。。。。。。。。。。");
        // 1. 执行认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        user.getUsername(),
                        user.getPassword()
                )
        );

        // 2. 将认证信息存入 SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 3. 从认证对象中获取用户信息
        Users users = (Users) authentication.getPrincipal();
        // 4. 生成 JWT Token
        String jwt = jwtUtils.generateToken(users);

        // 5. 返回 Token 给前端
        Map<String, String> response = new HashMap<>();
        response.put("token", jwt);
        return R.ok(response);
    }




}